package com.llxz.blog.acl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.llxz.blog.acl.entity.User;
import com.llxz.blog.acl.service.UserRoleService;
import com.llxz.blog.acl.service.UserService;
import com.llxz.blog.util.MD5Utils;
import com.llxz.blog.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author xzs
 * @description: date: 2021/9/4 9:36
 */
@RestController
@RequestMapping("/acl/user")
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    private UserRoleService userRoleService;


    @GetMapping("page/{current}/{limit}")
    public R page(@PathVariable Long current, @PathVariable Long limit, User user){
        Page<User> userPage = new Page<>(current,limit);
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(user.getUsername())){
            wrapper.like("name",user.getUsername());
        }

        IPage<User> pageModel = userService.page(userPage,wrapper);

        return R.ok().data("items",pageModel.getRecords()).data("total",pageModel.getTotal());
    }


    @PostMapping("add")
    public R add(@RequestBody User user){
        user.setPassword(MD5Utils.encrypt(user.getPassword()));
        userService.save(user);
        return R.ok();
    }

    @PutMapping("update")
    public R update(@RequestBody User user){
        userService.updateById(user);
        return R.ok();
    }

    @DeleteMapping("remove/{id}")
    public R remove(@PathVariable String id){
        userService.removeById(id);
        return R.ok();
    }

    @GetMapping("getRoleInfo/{userId}")
    public R getRoleInfo(@PathVariable String userId){
        Map<String, Object> roleByUserId = userRoleService.findRoleByUserId(userId);
        return R.ok().data(roleByUserId);
    }

    @PostMapping("assignRoles")
    public R assignRoles(@RequestParam String userId,@RequestParam String[] roleIds){
        userRoleService.assignRoles(userId,roleIds);
        return R.ok();
    }

}

